#include <func.h>

typedef struct train_s {
    int length;
    char data[1000];
} train_t;

int recvn(int netfd, void *buf, int length){
    int total = 0;
    char *p = (char *)buf;
    while(total < length){
        int ret = recv(netfd,p+total,length-total,0);
        if(ret == 0){
            return -1;
        }
        total += ret;
    }
    return 0;
}

int sendFile(int netfd,char *filename){
    int fd=open(filename,O_RDWR,0666);
    ERROR_CHECK(fd,-1,"open");
    
    train_t train;
    bzero(&train,sizeof(train));
    
    struct stat statbuf;
    fstat(fd,&statbuf);
    train.length=sizeof(statbuf.st_size);
    memcpy(train.data,&statbuf.st_size,train.length);
    
    send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);
    while(1){
        bzero(&train,sizeof(train));
        ssize_t ret = read(fd,train.data,sizeof(train.data));
        if(ret==0){
            break;
        }
        train.length=ret;
        send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);

    }
    close(fd);
    printf("上传完成\n");
    return 0;
}

int getsfile(int netfd,char *filename){
    int fd;
    ssize_t fileLength=0;
    if((fd=open(filename,O_RDWR,0666))!=-1){
        struct stat statbuf;
        fstat (fd,&statbuf);
        fileLength =  statbuf.st_size;
        send(netfd,&fileLength,sizeof(ssize_t),MSG_NOSIGNAL);
    }else{
        fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0666);
        send(netfd,&fileLength,sizeof(ssize_t),MSG_NOSIGNAL);
    }
    lseek(fd,fileLength-1,SEEK_SET);
    int length=0;
    off_t filesize=0;
    recvn(netfd,&length,sizeof(int));
    recvn(netfd,&filesize,length);
    off_t cursize = 0;
    off_t slice = filesize/10000;
    off_t lastsize = 0; 
    char buf[1024] = {0};
    while(1){
        length =0;
        recvn(netfd,&length,sizeof(int));
        //if(length != 1000){
        //    printf("length = %d\n", length);
        //}
        if(length == 0){
            break;
        }
        bzero(buf,sizeof(buf));
        recvn(netfd,buf,length);
        cursize += length;
        if(cursize - lastsize > slice){
            printf("%5.2lf%%\r",100.0 * cursize / filesize);
            fflush(stdout);
            lastsize = cursize;
        }
        write(fd,buf,length);
    }
    printf("100.00%%\n");
    printf("下载完成\n");
    close(fd);
    return 0;
}
